<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\CustomsExporter;
use App\Models\CustomsHarbour;
use Illuminate\Http\Request;

class CustomsHarbourController extends Controller
{
    /**
     * Title for current resource.
     * @var string
     */
    protected $title = '港口管理';


    public function index(Request $req): array
    {
        $all = $req->all();
        $per_page = $this->getPerPage($req);

        $qry = CustomsHarbour::query()
            ->orderBy('created_at','desc');

        // 名称
        if (isset($all['name'])) {
            $qry->where('name', 'like', '%'.$all['name'].'%');
        }
        // 类别
        if (isset($all['type'])) {
            $qry->where('type', 'like',"%{$all['type']}%");
        }

        $list = $qry->paginate($per_page);
        foreach($list->items() as $item) {
            $item->_type = @CustomsHarbour::TYPE[$item->type];
        }

        return $this->resSuccess('', $list);
    }

    /** 新增
     * @param Request $req
     * @return array
     */
    public function store(Request $req): array
    {
        $all = $req->all();
        $name = isset($all['name']) ? trim($all['name']) : '';
        if (!$name || !isset($all['name']) || !isset($all['type'])  ) {
            return $this->resError('信息不全');
        }
        $repeat = CustomsHarbour::where('name', $name)->where('type', $all['type'])->first();
        if ($repeat) {
            return $this->resError('名称“'.$name.'”，已存在！');
        }
        $obj = new CustomsHarbour($all);

        if ($obj->save()) {
            return $this->resSuccess();
        }
        return $this->resError();

    }

    /** 编辑
     * @param Request $req
     * @return array
     */
    public function update($id, Request $req): array
    {
        $all = $req->all();
        $name = isset($all['name']) ? trim($all['name']) : '';
        if (!$name  || !isset($all['type'])  ) {
            return $this->resError('信息不全');
        }
        if (!$obj = $this->find(new CustomsHarbour, $id)) {
            return $this->resError(self::debug());
        }

        $repeat = CustomsHarbour::where('name', $name)
            ->where('id','<>', $id)
            ->where('type', $all['type'])->first();
        if ($repeat) {
            return $this->resError('名称“'.$name.'”，已存在！');
        }

        $obj->fill($all);
        if ($obj->save()) {
            return $this->resSuccess();
        }
        return $this->resError();

    }

    // 删除
    public function destroy($id): array
    {
        if (parent::delete(new CustomsExporter(), $id)) {
            return $this->resSuccess();
        } else {
            return $this->resError(self::debug());
        }
    }

    public function export()
    {

    }


    /**
     * Make a grid builder.
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new CustomsHarbour());

        $grid->model()->orderBy('id','desc');
        $grid->filter(function ($filter) {
            $filter->disableIdFilter();
            $filter->column(3 / 12, function ($filer) {
                $filer->where(function ($query) {
                    $query->where('name', 'like', "%{$this->input}%");
                }, '港口名称');
            });
            $filter->column(3 / 12, function ($filer) {
                $filer->where(function ($query) {
                    $query->where('type', 'like', "%{$this->input}%");
                }, '类型')->select(CustomsHarbour::TYPE);
            });
        });
        $grid->column('id', 'ID');
        $grid->column('name', __('港口名称'));
        $grid->column('type', __('类型'))->using(CustomsHarbour::TYPE);
        $grid->column('country', __('国家'));
        $grid->column('city', __('城市'));

        $this->disableButton(['view']);
        return $grid;
    }

    /**
     * Make a show builder.
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(CustomsHarbour::findOrFail($id));
        $show->panel()->tools(function ($tools) {
            $tools->disableDelete();
        });
        $show->field('name', __('港口名称'));
        $show->field('type', __('类型'))->using(CustomsHarbour::TYPE);
        $show->field('country', __('国家'));
        $show->field('city', __('城市'));
        return $show;
    }

//    use \App\Traits\OperationLog;

    /**
     * Make a form builder.
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new CustomsHarbour());
        $form->text('name', __('港口名称'))->rules(function ($form) {
            return 'required|unique:' . (new CustomsHarbour())->getTable() . ',name,' . $form->model()->id . ',id,type,' . request()->get('type');
        })->required();
        $form->select('type', __('类型'))->options(CustomsHarbour::TYPE)->rules(function ($form) {
            return 'required|unique:' . (new CustomsHarbour())->getTable() . ',name,' . $form->model()->id . ',id,type,' . request()->get('type');
        })->required();
        $form->text('country', __('国家'))->required();
        $form->text('city', __('城市'))->required();

        $form->saving(function($form) {
            self::setOrigin($form);
        });
        // 操作日志
        $form->saved(function($form) {
            self::saveLog($form,  'name', $form->model()->id);
        });

        return $form;
    }
}
